package lf.day0109.travel.uilts;

import java.sql.*;

public class BaseDao {
    //定义了driver url username password 静态实例
    protected static String driver;
    protected static String url;
    protected static String username;
    protected static String password;
    //Connection数据库连接对象
    protected Connection conn;
    //PreparedStatement 预编译传输实例对象
    protected PreparedStatement pstmt;
    //ResultSet 查询结果集实例对象
    protected ResultSet rs;

    //1.建立数据库连接
    public Connection getConn(){
        //获取driver url username password 这四个参数对应值
        driver = ConfigManager.getInstance().getProperty("oracle.driver");
        url = ConfigManager.getInstance().getProperty("oracle.url");
        username = ConfigManager.getInstance().getProperty("oracle.usernameTravel");
        password = ConfigManager.getInstance().getProperty("oracle.password");
        driver = "oracle.jdbc.driver.OracleDriver";
        url = "jdbc:oracle:thin:@127.0.0.1:1521:orcl";
        username = "TRAVEL";
        password = "123456";
        try{
            //①加载数据库驱动
            Class.forName(driver);
            //②建立数据库连接对象
            conn = DriverManager.getConnection(url,username,password);
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }

        return conn;
    }
    //2.关闭数据库连接
    public void closeAllConn(Connection conn,PreparedStatement pstmt,ResultSet rs){
        try{
            if(rs != null){
                rs.close();
            }
            if(pstmt != null){
                pstmt.close();
            }
            if(conn != null){
                conn.close();
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }

    //3.定义公共的查询方法
    public ResultSet executeQuery(String sql,Object...params){
        conn = getConn();
        try {
            pstmt = conn.prepareStatement(sql);
            for (int i = 0; i < params.length; i++) {
                pstmt.setObject(i+1,params[i]);
            }
            rs = pstmt.executeQuery();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return rs;
    }

    //4.定义公共的增删改方法
    public int executeUpdate(String sql,Object...params){
        int updateRes = 0;
        conn = getConn();
        try {
            pstmt = conn.prepareStatement(sql);
            for (int i = 0; i < params.length; i++) {
                pstmt.setObject(i+1,params[i]);
            }
            updateRes = pstmt.executeUpdate();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            closeAllConn(conn,pstmt,rs);
        }
        return updateRes;
    }


    public static void main(String[] args) {
        BaseDao bd = new BaseDao();

        System.out.println(bd.getConn());
    }
}
